<script setup>
import { like } from '@/api/article'
import { showToast } from 'vant'
import { useRouter } from 'vue-router'

const router = useRouter()
const props = defineProps({
  article: {
    type: Object,
    required: true
  }
})

const handleLike = async (e) => {
  e.stopPropagation()
  try {
    await like(props.article.id)
    props.article.likeStatus = props.article.likeStatus === 0 ? 1 : 0
    props.article.liked = props.article.likeStatus === 1 
      ? props.article.liked + 1 
      : props.article.liked - 1
  } catch (error) {
    showToast('操作失败')
  }
}

const goToDetail = () => {
  router.push(`/article/${props.article.id}`)
}
</script>

<template>
  <div class="article-item" @click="goToDetail">
    <div class="article-img">
      <img :src="article.imagesList[0]" alt="">
    </div>
    <div class="article-title">{{ article.title }}</div>
    <div class="article-info">
      <div class="user-info">
        <img :src="article.userInfo.avatar" alt="" class="avatar">
        <span class="nickname">{{ article.userInfo.username }}</span>
      </div>
      <div class="likes" @click="handleLike">
        <van-icon 
          :name="article.likeStatus === 0 ? 'like-o' : 'like'" 
          :color="article.likeStatus === 0 ? '#666' : '#FF653F'" 
        />
        <span>{{ article.liked }}</span>
      </div>
    </div>
  </div>
</template>

<style scoped lang="scss">
.article-item {
  background: #fff;
  border-radius: 8px;
  overflow: hidden;
  box-shadow: 0 2px 8px rgba(0,0,0,0.1);
  .article-img {
    width: 100%;
    height: 0;
    padding-bottom: 100%;
    position: relative;
    img {
      position: absolute;
      width: 100%;
      height: 100%;
      object-fit: cover;
    }
  }
  .article-title {
    padding: 8px;
    font-size: 14px;
    font-weight: bold;
    overflow: hidden;
    text-overflow: ellipsis;
    display: -webkit-box;
    -webkit-line-clamp: 2;
    -webkit-box-orient: vertical;
  }
  .article-info {
    padding: 8px;
    display: flex;
    justify-content: space-between;
    align-items: center;
    .user-info {
      display: flex;
      align-items: center;
      .avatar {
        width: 24px;
        height: 24px;
        border-radius: 50%;
        margin-right: 6px;
      }
      .nickname {
        font-size: 12px;
        color: #666;
      }
    }
    .likes {
      display: flex;
      align-items: center;
      color: #666;
      font-size: 12px;
      .van-icon {
        margin-right: 4px;
      }
    }
  }
}
</style> 